package com.smarthouse.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.smarthouse.model.FaceCompareResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import okhttp3.*;

@Service
public class FaceRecognitionService {
    private static final Logger logger = LoggerFactory.getLogger(FaceRecognitionService.class);

    private static final String API_KEY = "pkf9ECBpWtoqKy9GeRz79HC3";
    private static final String SECRET_KEY = "NV5lJTcJH3AuSep6zMYipjz9vY3zIzKT";
    private String accessToken;

    public FaceCompareResponse compareFaces(String image1Base64) throws Exception {
        // 获取access token
        if (accessToken == null) {
            accessToken = getAccessToken();
        }

        // 构建请求体
        JSONObject requestJson = new JSONObject();
        requestJson.put("image", image1Base64);
        requestJson.put("image_type", "BASE64");
        requestJson.put("group_id_list", "A");
        requestJson.put("quality_control", "NORMAL");
        requestJson.put("liveness_control", "NORMAL");
        requestJson.put("max_user_num", 1);

        // 发送请求到百度API
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(
            MediaType.parse("application/json"), 
            requestJson.toString()
        );

        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + accessToken)
            .post(body)
            .addHeader("Content-Type", "application/json")
            .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            logger.info("百度API响应: {}", responseBody);
            
            // 使用FastJSON2解析响应
            JSONObject result = JSON.parseObject(responseBody);
            
            // 检查错误码
            Integer errorCode = result.getInteger("error_code");
            if (errorCode != null && errorCode == 0) {
                JSONObject resultObj = result.getJSONObject("result");
                if (resultObj != null) {
                    // 获取用户列表
                    var userList = resultObj.getJSONArray("user_list");
                    if (userList != null && !userList.isEmpty()) {
                        // 获取第一个用户的分数
                        JSONObject firstUser = userList.getJSONObject(0);
                        double score = firstUser.getDoubleValue("score");
                        //判断返回值
                        if (score >= 80) {
                            return new FaceCompareResponse(score, true);
                        }else {
                            return new FaceCompareResponse(score, false);
                        }

                    }
                }
                return new FaceCompareResponse(0, false);
            }

            String errorMsg = result.getString("error_msg");
            throw new RuntimeException("人脸搜索失败: " + (errorMsg != null ? errorMsg : "未知错误"));
        }
    }

    private String getAccessToken() throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/oauth/2.0/token?" +
                "grant_type=client_credentials&" +
                "client_id=" + API_KEY + "&" +
                "client_secret=" + SECRET_KEY)
            .post(RequestBody.create(null, new byte[0]))
            .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            logger.info("获取token响应: {}", responseBody);
            
            // 使用FastJSON2解析响应
            JSONObject result = JSON.parseObject(responseBody);
            String token = result.getString("access_token");
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("获取access token失败");
            }
            return token;
        }
    }
}